package br.sed.theenemy.presentation.servlets;

import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import br.sed.theenemy.business.exception.DBException;
import br.sed.theenemy.business.services.Services;
import br.sed.theenemy.model.bean.User;
import br.sed.theenemy.presentation.EnemyConstants;
import br.sed.theenemy.presentation.EnemyErrorConstants;
import br.sed.theenemy.presentation.action.json.exception.ExpectedException;
import br.sed.theenemy.presentation.action.json.exception.IdentifiedException;
import br.sed.theenemy.presentation.servlets.json.JSONBaseServlet;
import br.sed.theenemy.presentation.vo.UserVO;

/**
 * 
 * @author Julio CB
 * @email jcbjulio@gmail.com
 * 
 */
public class FindByNameServlet extends JSONBaseServlet {

	private static final long serialVersionUID = -5120099177751980303L;

	@Override
	protected Object executeJSON(HttpServletRequest request,
			HttpServletResponse response) throws ExpectedException,
			IdentifiedException {
		Services services = Services.getInstance();
		
		List<String> errors =  new ArrayList<String>();
		
		if (errors.size()!=0){
			throw new ExpectedException(EnemyErrorConstants.MISSING_PARAM, errors);
		}
		String name = request.getParameter("name");
		Integer page = Integer.parseInt(request.getParameter("page"));
		if (page == null || page <= 0){
			throw new ExpectedException(EnemyErrorConstants.INCORRECT_PARAM);
		}
		Integer max = Integer.parseInt(request.getParameter("max"));
		if (max == null || max <= 0 || max > EnemyConstants.MAX_PAGE_ITENS){
			throw new ExpectedException(EnemyErrorConstants.INCORRECT_PARAM);
		}
		
		List<User> userList = null;
		try {
			 userList = services.findUserByPieceOfName(name, page, max);
		} catch (DBException e) {
			throw new ExpectedException(EnemyErrorConstants.DB_EXCEPTION);
		}
		
		List<UserVO> userListVO = new ArrayList<UserVO>();
		for (User user: userList){
			UserVO userVO = new UserVO(user);
			userListVO.add(userVO);
		}

		return userListVO;
	}
}
